/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedBean;

import Merlion.CRM.entity.BillingAddressEntity;
import Merlion.CRM.entity.ClientEntity;
import Merlion.CRM.entity.LineEntryEntity;

//import CRM.ProductCRMEntity;
import Merlion.CRM.entity.PricebookEntity;
import Merlion.CRM.bean.SalesLeadModuleRemote;
import Merlion.CRM.bean.SalesOrderProcessingModuleRemote;
import Merlion.CRM.entity.ShippingAddressEntity;
import Merlion.util.state.AddressState;
import Merlion.util.state.ClientState;
import Merlion.util.state.ContactState;
import Merlion.util.state.LineEntryState;
import Merlion.util.state.ProductState;
import Merlion.util.state.SalesDocumentState;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseEvent;
import javax.servlet.ServletException;
import org.primefaces.event.RowEditEvent;


@ManagedBean(name = "SalesOrderManagedBean")
@ViewScoped
public class SalesOrderManagedBean implements Serializable {
 
    private LineEntryState lineEntry = new LineEntryState();
    private List<LineEntryState> lineEntryList = new ArrayList<LineEntryState>();
    private Long purchaseOrderInput;
    private SalesDocumentState newSalesOrder = new SalesDocumentState();
    private List<SalesDocumentState> purchaseOrderList;
    private SalesDocumentState selectedSalesOrder;
    private SalesDocumentState[] selectedSalesOrders;
    private ClientEntity client;
    private List<LineEntryState> productList;
    private SalesDocumentState selectedViewSalesOrder;
    private SalesDocumentState selectedPrintSalesOrder;
    private List<ClientState> clientList;
    private List<SalesDocumentState> salesOrderList;
    private List<LineEntryState> selectedProductList;
    private List<ContactState> contactList;
    private boolean editMode;
    private Long productId;
    private Long selectedPrintSalesOrderID;
    private int quantity;
    private double listPrice;
    private String type;
    private PricebookEntity pricebook;
    private List<PricebookEntity> pricebookList;
    private double totalPrice;
    private String pricingType;
    private List<AddressState> billingAddress;
    private List<AddressState> shippingAddress;
    private AddressState selectedBillingAddress;
    private AddressState selectedShippingAddress;
    private List<ContactState> selectedContactList;
    @EJB
    private SalesOrderProcessingModuleRemote sop;
    @EJB
    private SalesLeadModuleRemote smb;

    public List<ContactState> getSelectedContactList() {
        if (selectedContactList == null) {
            if (selectedViewSalesOrder != null) {
                selectedContactList = smb.viewContactsForClients(selectedViewSalesOrder.getClientId());
            }
        }
        return selectedContactList;
    }

    public void setSelectedContactList(List<ContactState> selectedContactList) {
        this.selectedContactList = selectedContactList;
    }

    public String reinit() {

        lineEntry = new LineEntryState();

        return null;
    }

    public List<LineEntryState> getProductList() {

        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        System.out.println("Get Product List");               
        return productList;
    }

    public void setProductList(List<LineEntryState> productList) {
        this.productList = productList;
    }

    public List<SalesDocumentState> getPurchaseOrderList() {
        if (purchaseOrderList == null) {
            purchaseOrderList = sop.viewPurchaseOrdersforSO();
        }
        return purchaseOrderList;
    }

    public void setPurchaseOrderList(List<SalesDocumentState> purchaseOrderList) {
        this.purchaseOrderList = purchaseOrderList;
    }

    public List<LineEntryState> getSelectedProductList() {
        return selectedProductList;
    }

    public void setSelectedProductList(List<LineEntryState> selectedProductList) {
        this.selectedProductList = selectedProductList;
    }

    public List<ClientState> getClientList() {
        if (clientList == null) {
            clientList = smb.viewCustomers();
        }
        return clientList;
    }

    public void setClientList(List<ClientState> clientList) {
        this.clientList = clientList;
    }


    public SalesDocumentState getNewSalesOrder() {
        return newSalesOrder;
    }

    public void setNewSalesOrder(SalesDocumentState newSalesOrder) {
        this.newSalesOrder = newSalesOrder;
    }

    public SalesDocumentState getSelectedViewSalesOrder() {
        return selectedViewSalesOrder;
    }

    public void setSelectedViewSalesOrder(SalesDocumentState selectedViewSalesOrder) {
        this.selectedViewSalesOrder = selectedViewSalesOrder;
        if (selectedViewSalesOrder != null) {
            System.out.println("View SalesOrder NOT NULL");
        }
        this.selectedViewSalesOrder = selectedViewSalesOrder;
        System.out.println("ID : " + selectedViewSalesOrder.getId());
        selectedProductList = sop.viewProductListforSalesDocument(selectedViewSalesOrder.getId());
        this.setSelectedProductList(selectedProductList);
    }

    public void initView2(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
        if (salesOrderList == null) {
            salesOrderList = sop.viewSalesOrders();
        }
    }

    public void initView(PhaseEvent event) {
        FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    }

    public SalesOrderManagedBean() {

        lineEntry = new LineEntryState();

    }

    public LineEntryState getLineEntry() {
        return lineEntry;
    }

    public void setLineEntry(LineEntryState lineEntry) {
        this.lineEntry = lineEntry;
    }

    public List<LineEntryState> getLineEntryList() {
        System.out.println("GET LINE ENTRY LIST");
        return lineEntryList;
    }

    public void setLineEntryList(List<LineEntryState> lineEntryList) {
        System.out.println("SET LINE ENTRY LIST");
        this.lineEntryList = lineEntryList;
    }

    public void addSalesOrder2(ActionEvent event) {

        System.out.println(":::WEB::: Add Sales Order2");

        Long soID = newSalesOrder.getId();
        Date dateIssued = newSalesOrder.getDateIssued();
        Long clientID = newSalesOrder.getClientId();
        Long contactID = newSalesOrder.getContactId();
        Long epoID = newSalesOrder.getPoID();
        String status = newSalesOrder.getStatus();
        String ATP = newSalesOrder.getATPCheckStatus();
        String credit = newSalesOrder.getCreditCheckStatus();

        String billStreet = newSalesOrder.getBillingStreet();
        String billState = newSalesOrder.getBillingState();
        String billCity = newSalesOrder.getBillingCity();
        String billCode = newSalesOrder.getBillingCode();
        String billCountry = newSalesOrder.getBillingCountry();


        String shipStreet = newSalesOrder.getShippingStreet();
        String shipState = newSalesOrder.getShippingState();
        String shipCity = newSalesOrder.getShippingCity();
        String shipCode = newSalesOrder.getShippingCode();
        String shipCountry = newSalesOrder.getShippingCountry();

        String description = newSalesOrder.getDescription();
        String docName = newSalesOrder.getDocumentName();
        String shippingMethod = newSalesOrder.getShippingMethod();
        String shippingRule = newSalesOrder.getShippingRule();
        String paymentMethod = newSalesOrder.getPaymentMethod();
        String invoiceRule = newSalesOrder.getInvoiceRule();
        String freightCostRule = newSalesOrder.getFreightCostRule();
        String currency = newSalesOrder.getCurrency();
        Date dueDate = newSalesOrder.getDueDate();
        String priority = "Medium";

        Long billingId = Long.parseLong("0");
        if (newSalesOrder.getBillingId() != null) {
            System.out.println("Billing ID not null!");
            billingId = newSalesOrder.getBillingId();
            smb.editBillingAddress(billingId, billStreet, billCity, billState, billCode, billCountry);
        }
        Long shippingId = Long.parseLong("0");
        if (newSalesOrder.getShippingId() != null) {
            System.out.println("Shipping ID not null!");
            shippingId = newSalesOrder.getShippingId();
            smb.editShippingAddress(shippingId, shipStreet, shipCity, shipState, shipCode, shipCountry);
        }

        System.out.println("Customer ID is : " + clientID);

        if (!lineEntryList.isEmpty()) {
            System.out.println("Products not null");
            System.out.println("ID is : " + lineEntryList.get(0).getId());
        }
        System.out.println(":::WEB::: Calling addSalesOrder2()");
 

        sop.addSalesOrder(dateIssued, clientID, contactID, lineEntryList, purchaseOrderInput, billingId,
                shippingId, description, dueDate, docName, shippingMethod, shippingRule,
                invoiceRule, paymentMethod, priority, freightCostRule, currency, pricingType);
        System.out.println(":::WEB::: Add Sales Order 2 done");

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesOrderSuccessfulRegistration.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }



    }

    public void onEditRow(RowEditEvent event) {

        System.out.println(":::WEB::: On Edit Row");
        SalesDocumentState eDocument = (SalesDocumentState) event.getObject();


        if (eDocument != null) {
            System.out.println(":::WEB::: Edited document not null");
    
            String eStatus = eDocument.getStatus();
            String ATPCheckStatus = eDocument.getATPCheckStatus();
            String creditCheckStatus = eDocument.getCreditCheckStatus();
            Date eDateIssued = eDocument.getDateIssued();
            Long clientId = eDocument.getClientId();
            Long soId = eDocument.getId();
            System.out.println("Sales Order ID " + soId);
            Long poID = eDocument.getPoID();
            System.out.println("Purchase Order ID is " + poID);
            Long eContactId = eDocument.getContactId();

            String eBillStreet = eDocument.getBillingStreet();
            String eBillState = eDocument.getBillingState();
            String eBillCity = eDocument.getBillingCity();
            String eBillCode = eDocument.getBillingCode();
            String eBillCountry = eDocument.getBillingCountry();
            Long eBillId = eDocument.getBillingId();
            smb.editBillingAddress(eBillId, eBillStreet, eBillCity, eBillState, eBillCode, eBillCountry);

            String eShipStreet = eDocument.getShippingStreet();
            String eShipState = eDocument.getShippingState();
            String eShipCity = eDocument.getShippingCity();
            String eShipCode = eDocument.getShippingCode();
            String eShipCountry = eDocument.getShippingCountry();
            Long eShipId = eDocument.getShippingId();
            smb.editShippingAddress(eShipId, eShipStreet, eShipCity, eShipState, eShipCode, eShipCountry);

            String eDesc = eDocument.getDescription();
            String eDocName = eDocument.getDocumentName();
            String eShippingMethod = eDocument.getShippingMethod();
            String eShippingRule = eDocument.getShippingRule();
            Date eDueDate = eDocument.getDueDate();
            String eInvoiceRule = eDocument.getInvoiceRule();
            String ePaymentMethod = eDocument.getPaymentMethod();
            String eFreightCostRule = eDocument.getFreightCostRule();
            String eCurrency = eDocument.getCurrency();
            String ePriority = eDocument.getPriority();
    
            System.out.println(":::WEB::: Calling Edit Sales Order");
            sop.editSalesOrder(soId, eDateIssued, clientId, eContactId, poID, eStatus, ATPCheckStatus, creditCheckStatus,
                    eDesc, eDueDate, eDocName, eShippingMethod, eShippingRule, eInvoiceRule,
                    ePaymentMethod, ePriority, eFreightCostRule, eCurrency, eBillId, eShipId);
        } else {
            System.out.println(":::WEB::: Edited sales order is null");
        }

    }

    public void onEditLineEntry(RowEditEvent event) {

        System.out.println(":::WEB::: On Edit Line Entry");
        LineEntryState line = (LineEntryState) event.getObject();

        if (line != null) {
            System.out.println(":::WEB::: Edited line entry not null");
            int indicativeLeadTime = line.getIndicativeLeadTime();
            Long id = line.getId();
            int amtShipped = line.getAmountShipped();
            int amtInvoiced = line.getAmountInvoiced();
            System.out.println(":::WEB::: Calling Update Lead Time");
            sop.updateLineEntry(id, indicativeLeadTime, amtShipped, amtInvoiced);
        } else {
            System.out.println(":::WEB::: Edited line entry is null");
        }

    }

    public void requestForInvoice() {
        System.out.println(":::WEB::: Request for invoice");

        if (selectedSalesOrders != null) {
            System.out.println(":::WEB::: If selected sales orders not null");
            for (int i = 0; i < selectedSalesOrders.length; i++) {
                System.out.println("selectedSalesOrders i: " + i + " - " + selectedSalesOrders[i].getId());
                sop.requestForInvoice(selectedSalesOrders[i].getClientId(), selectedSalesOrders[i].getId());
            }
        } else {
            System.out.println(":::WEB::: Selected sales orders are null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public void deleteSalesOrders() {
        System.out.println(":::WEB::: Delete Sales Orders");

        if (selectedSalesOrders != null) {
            System.out.println(":::WEB::: If selected sales orders not null");
            for (int i = 0; i < selectedSalesOrders.length; i++) {
                System.out.println("selectedSalesOrders i: " + i + " - " + selectedSalesOrders[i].getId());
                sop.deleteSalesOrder(selectedSalesOrders[i].getId());
            }
        } else {
            System.out.println(":::WEB::: Selected sales orders are null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public void cancelDelete() {
        for (SalesDocumentState sdState : selectedSalesOrders) {
            sdState = null;
        }
        if (selectedSalesOrders == null) {
            System.out.println(":::WEB::: Deletion of Purchase Orders cancelled");

        } else {
            System.out.println(":::WEB::: Deletion of Purchase Orders are not cancelled");
        }

    }

    public void delete(ActionEvent Event) {

        System.out.println(":::WEB::: Delete Sales Order");

        if (selectedSalesOrder != null) {
            System.out.println(":::WEB::: Selected Sales Order not null");
            Long salesOrderId = selectedSalesOrder.getId();
            System.out.println(":::WEB::: Sales Order ID is : " + salesOrderId);
            sop.deleteSalesOrder(salesOrderId);
            System.out.println(":::WEB::: Deletion done");
        } else {
            System.out.println(":::WEB::: Selected Sales Order is null");
        }

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }


    public Long getPurchaseOrderInput() {
        return purchaseOrderInput;
    }

    public void setPurchaseOrderInput(Long purchaseOrderInput) {
        this.purchaseOrderInput = purchaseOrderInput;
    }

    public ClientEntity getClient() {
        return client;
    }

    public void setClient(ClientEntity client) {
        this.client = client;
    }

    public List<SalesDocumentState> getSalesOrderList() {
        return salesOrderList;
    }

    public void setSalesOrderList(List<SalesDocumentState> salesOrderList) {
        this.salesOrderList = salesOrderList;
    }

    public SalesDocumentState getSelectedSalesOrder() {
        return selectedSalesOrder;
    }

    public void setSelectedSalesOrder(SalesDocumentState selectedSalesOrder) {
        this.selectedSalesOrder = selectedSalesOrder;
    }

    public SalesDocumentState[] getSelectedSalesOrders() {
        return selectedSalesOrders;
    }

    public void setSelectedSalesOrders(SalesDocumentState[] selectedSalesOrders) {
        this.selectedSalesOrders = selectedSalesOrders;
    }


    public boolean isEditMode() {
        return editMode;
    }

    public void setEditMode(boolean editMode) {
        this.editMode = editMode;
    }

    public void save(ActionEvent event) {
        System.out.println(":::WEB::: Save Edit SO");

        Long cSoID = selectedViewSalesOrder.getId();
        Date cDateIssued = selectedViewSalesOrder.getDateIssued();
        Long cClientID = selectedViewSalesOrder.getClientId();
        Long cPoID = selectedViewSalesOrder.getPoID();
        String cStatus = selectedViewSalesOrder.getStatus();
        String cATP = selectedViewSalesOrder.getATPCheckStatus();
        String cCredit = selectedViewSalesOrder.getCreditCheckStatus();
        Long cContactID = selectedViewSalesOrder.getContactId();

        String cBillStreet = selectedViewSalesOrder.getBillingStreet();
        String cBillState = selectedViewSalesOrder.getBillingState();
        String cBillCity = selectedViewSalesOrder.getBillingCity();
        String cBillCode = selectedViewSalesOrder.getBillingCode();
        String cBillCountry = selectedViewSalesOrder.getBillingCountry();
        Long cBillId = selectedViewSalesOrder.getBillingId();
        smb.editBillingAddress(cBillId, cBillStreet, cBillCity, cBillState, cBillCode, cBillCountry);

        String cShipStreet = selectedViewSalesOrder.getShippingStreet();
        String cShipState = selectedViewSalesOrder.getShippingState();
        String cShipCity = selectedViewSalesOrder.getShippingCity();
        String cShipCode = selectedViewSalesOrder.getShippingCode();
        String cShipCountry = selectedViewSalesOrder.getShippingCountry();
        Long cShipId = selectedViewSalesOrder.getShippingId();
        smb.editShippingAddress(cShipId, cShipStreet, cShipCity, cShipState, cShipCode, cShipCountry);


        String cDescription = selectedViewSalesOrder.getDescription();
        String cDocName = selectedViewSalesOrder.getDocumentName();
        String cShippingMethod = selectedViewSalesOrder.getShippingMethod();
        String cShippingRule = selectedViewSalesOrder.getShippingRule();
        String cPaymentMethod = selectedViewSalesOrder.getPaymentMethod();
        String cInvoiceRule = selectedViewSalesOrder.getInvoiceRule();
        String cFreightCostRule = selectedViewSalesOrder.getFreightCostRule();
        String cCurrency = selectedViewSalesOrder.getCurrency();
        Date cDueDate = selectedViewSalesOrder.getDueDate();
        String cPriority = selectedViewSalesOrder.getPriority();


        System.out.println("SO ID is :" + cSoID);
        System.out.println(":::WEB::: Calling edit SO");



        sop.editSalesOrder(cSoID, cDateIssued, cClientID, cContactID, cPoID, cStatus, cATP, cCredit,
                cDescription, cDueDate, cDocName, cShippingMethod,
                cShippingRule, cInvoiceRule, cPaymentMethod, cPriority, cFreightCostRule,
                cCurrency, cBillId, cShipId);

        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect("salesOrders.xhtml");
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    public PricebookEntity getPricebook() {

        return pricebook;
    }

    public void setPricebook(PricebookEntity pricebook) {
        System.out.println("SET PRICEBOOK");

        this.pricebook = pricebook;

    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        System.out.println("Set total price");
        this.totalPrice = totalPrice;
    }

    public String getPricingType() {
        return pricingType;
    }

    public void setPricingType(String pricingType) {
        this.pricingType = pricingType;
    }

    public List<PricebookEntity> getPricebookList() {
        System.out.println("GET PRICEBOOK LIST");

        if (pricebookList == null) {

            System.out.println("GET from bean");
            pricebookList = sop.getPricebookList();
        
        }
        return pricebookList;
    }

    public void setPricebookList(List<PricebookEntity> pricebookList) {
        System.out.println("SET pricebook List");
        this.pricebookList = pricebookList;
    }

    public double getListPrice() {
        return listPrice;
    }

    public void setListPrice(double listPrice) {
        System.out.println("SET LIST PRICE");
        this.listPrice = listPrice;
    }

    public void handlePricebookChange() {
        System.out.println("HANDLE PRICEBOOK CHANGE");
        if (lineEntry.getPricebookId() != null) {
            System.out.println("Pricebook not null");
            System.out.println("Type " + type);
            System.out.println("quantity" + lineEntry.getQuantity());

            listPrice = sop.getListPrice(lineEntry.getQuantity(), type, lineEntry.getPricebookId());
            lineEntry.setPrice(listPrice);
            System.out.println(lineEntry.getPrice());
            double total = sop.getTotalPrice(lineEntry, pricingType);
            System.out.println("Total " + total);
            lineEntry.setTotalPrice(total);
        }
    }

    public void onRowEdit(RowEditEvent event) {

        System.out.println(":::WEB::: On Edit Row");
        LineEntryState eLine = (LineEntryState) event.getObject();


        int eQuantity = eLine.getQuantity();
        double newPrice = eLine.getPrice();
        eLine.setPrice(newPrice);
        eLine.setQuantity(eQuantity);
        double total = sop.getTotalPrice(eLine, pricingType);

        eLine.setTotalPrice(total);
    }

    public void handleProductChange() {
        System.out.println("HANDLE PRODUCT CHANGE");
        if (lineEntry.getItemId() != null) {
            List<PricebookEntity> list = sop.getPricebook(lineEntry.getItemId());
            System.out.println("Product is not empty");
            this.setPricebookList(list);
            ProductState product = sop.searchProduct(lineEntry.getItemId());
            lineEntry.setItemName(product.getItemName());
            lineEntry.setBasePrice(product.getPrice());
        }
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public List<AddressState> getBillingAddress() {
        if (billingAddress == null) {
            billingAddress = sop.getBillingAddressList();
        }
        return billingAddress;
    }

    public void setBillingAddress(List<AddressState> billingAddress) {
        this.billingAddress = billingAddress;
    }

    public List<AddressState> getShippingAddress() {
        if (shippingAddress == null) {
            shippingAddress = sop.getShippingAddressList();
        }
        return shippingAddress;
    }

    public void setShippingAddress(List<AddressState> shippingAddress) {
        this.shippingAddress = shippingAddress;
    }

    public void handleClientChange() {
        System.out.println("Handle client change");
        if (newSalesOrder.getClientId() != null) {
            ClientState clState = smb.searchClient(newSalesOrder.getClientId());
            String bType = clState.getBusinessType();
            this.setType(bType);

            if (clState.getClientType().equals("CU")) {
                System.out.println("Set billing and shipping address");
                List<AddressState> addressList = clState.getAddressList();
                List<ContactState> cList = smb.viewContactsForClients(clState.getId());
                List<AddressState> billingAddressList = new ArrayList<AddressState>();
                List<AddressState> shippingAddressList = new ArrayList<AddressState>();
                for (Object o : addressList) {
                    AddressState as = (AddressState) o;
                    if (as.getType().equals("B")) {
                        billingAddressList.add(as);
                    } else if (as.getType().equals("S")) {
                        shippingAddressList.add(as);
                    }
                }
                this.setBillingAddress(billingAddressList);
                this.setShippingAddress(shippingAddressList);
                this.setContactList(cList);
            }
        }
    }

    public void handlePriceChange() {
        System.out.println("Handle price change");
        if (lineEntry.getPrice() != 0) {
            System.out.println("Price " + lineEntry.getPrice());
            double total = sop.getTotalPrice(lineEntry, pricingType);
            lineEntry.setTotalPrice(total);
        }
    }

    public void handleSalesDocumentChange() {
        System.out.println("HANDLE SALES DOCUMENT CHANGE");
        if (purchaseOrderInput != null) {
            SalesDocumentState poState = sop.searchPurchaseOrder(purchaseOrderInput);
            Long salesDocClient = poState.getClientId();
            System.out.println("Sales doc client : " + salesDocClient);
            newSalesOrder.setClientId(salesDocClient);
            ClientState clState = smb.searchClient(newSalesOrder.getClientId());
            String bType = clState.getBusinessType();
            this.setType(bType);
            String pType = poState.getPricingType();
            this.setPricingType(pType);

            handleClientChange();

            newSalesOrder.setShippingId(poState.getShippingId());
            newSalesOrder.setBillingId(poState.getBillingId());

            handleShippingAddressChange();
            handleBillingAddressChange();
            System.out.println("Set delivery and payment information");
            newSalesOrder.setShippingRule(poState.getShippingRule());
            newSalesOrder.setShippingMethod(poState.getShippingMethod());
            newSalesOrder.setFreightCostRule(poState.getFreightCostRule());
            newSalesOrder.setPaymentMethod(poState.getPaymentMethod());
            newSalesOrder.setInvoiceRule(poState.getInvoiceRule());
            newSalesOrder.setCurrency(poState.getCurrency());

            System.out.println("Getting line entry list from quotation");
            Collection<LineEntryEntity> collectionList = poState.getLineEntryList();
            List<LineEntryEntity> list = new ArrayList<LineEntryEntity>(collectionList);
            List<LineEntryState> newList = new ArrayList<LineEntryState>();
            for (Object o : list) {
                LineEntryEntity line = (LineEntryEntity) o;
                LineEntryState a = new LineEntryState();
                a.setBasePrice(line.getBasePrice());
                a.setItemId(line.getItemId());
                a.setTotalPrice(line.getTotalLinePrice());
                a.setQuantity(line.getQuantity());
                a.setPrice(line.getPrice());
                a.setPricebookId(line.getPricebookId());
                a.setIndicativeLeadTime(line.getLeadTime());
                a.setItemName(line.getItemName());
                newList.add(a);
            }
            this.setProductList(newList);
            this.setLineEntryList(newList);

        }
    }


    public List<ContactState> getContactList() {
        if (contactList == null) {
            contactList = smb.viewContacts();
        }
        return contactList;
    }

    public void setContactList(List<ContactState> contactList) {
        this.contactList = contactList;
    }

    public void handleBillingAddressChange() {
        System.out.println("Handle billing Address Change");

        if (newSalesOrder.getBillingId() != null) {
            AddressState ba = sop.searchBillingAddress(newSalesOrder.getBillingId());
            newSalesOrder.setBillingStreet(ba.getStreet());
            newSalesOrder.setBillingCity(ba.getCity());
            newSalesOrder.setBillingState(ba.getState());
            newSalesOrder.setBillingCode(ba.getCode());
            newSalesOrder.setBillingCountry(ba.getCountry());
        }

    }

    public void handleShippingAddressChange() {
        System.out.println("Handle Shipping Address Change");
        System.out.println("shipping id" + newSalesOrder.getShippingId());
        if (newSalesOrder.getShippingId() != null) {
            AddressState sa = sop.searchShippingAddress(newSalesOrder.getShippingId());
            newSalesOrder.setShippingStreet(sa.getStreet());
            newSalesOrder.setShippingCity(sa.getCity());
            newSalesOrder.setShippingState(sa.getState());
            newSalesOrder.setShippingCode(sa.getCode());
            newSalesOrder.setShippingCountry(sa.getCountry());
        }

    }

    /**
     * @return the selectedPrintSalesOrder
     */
    public SalesDocumentState getSelectedPrintSalesOrder() {
        return selectedPrintSalesOrder;
    }

    /**
     * @param selectedPrintSalesOrder the selectedPrintSalesOrder to set
     */
    public void setSelectedPrintSalesOrder(SalesDocumentState selectedPrintSalesOrder) {
        System.out.println("SET SELECTED PRINT SALES ORDER");
        if(selectedPrintSalesOrder!=null){System.out.println("SALES ORDER NOT NULL");}
        this.selectedPrintSalesOrder = selectedPrintSalesOrder;
        System.out.println("ID : "+selectedPrintSalesOrder.getId());
        this.setSelectedPrintSalesOrderID(selectedPrintSalesOrder.getId());
        
        //FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectedViewInquiryID",selectedViewInquiryID);
        selectedProductList=sop.viewProductListforSalesDocument(selectedPrintSalesOrder.getId());
        this.setSelectedProductList(selectedProductList);
    }

    /**
     * @return the selectedPrintSalesOrderID
     */
    public Long getSelectedPrintSalesOrderID() {
        return selectedPrintSalesOrderID;
    }

    /**
     * @param selectedPrintSalesOrderID the selectedPrintSalesOrderID to set
     */
    public void setSelectedPrintSalesOrderID(Long selectedPrintSalesOrderID) {
        this.selectedPrintSalesOrderID = selectedPrintSalesOrderID;
    }

    public void checkSalesDocumentValidity() {
        sop.checkSalesDocumentValidity();
    }
    
      public void generateSalesOrderReport(ActionEvent event) throws ServletException{
                 System.out.println("TRY TO GENERATE REPORT ");
        try
        { 
            if(selectedPrintSalesOrder != null){
            System.out.print("managedbean1");
           //  FacesContext.getCurrentInstance().getExternalContext().getFlash().put("selectedPrintInquiry", selectedPrintInquiry);
             Long selectedPrintSalesOrderID = selectedPrintSalesOrder.getId();
             FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("selectedPrintSalesOrderID", selectedPrintSalesOrderID);
             FacesContext.getCurrentInstance().getExternalContext().redirect("http://localhost:8181/MerlionERP-war/salesOrderServlet");
            System.out.print("managedbean2");
            }else{
               System.out.println("selectedPrintSalesOrder is null"); 
            }
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }

}
